#include "smse2kincludes.h"
#include "KSS_MMU.h"

CKSSMMU_Program::CKSSMMU_Program() {

}

UINT8 CKSSMMU_Program::Read8(UINT64 _off) {
	UINT32 offset = _off;
	//Msg("Read: %4X = %2X\n",offset, memspace[offset]);
	
	offset &= 0xffff;
	
	// Unhandled memory read, just throw it to memspace
	return this->memspace[offset];
}

void CKSSMMU_Program::Write8(UINT64 offset, UINT8 data) {

	// This copypaste courtesy of msxplug
	if((offset==0x9000||offset==0xB000||offset==0xBFFE))
    {
      if(offset==0x9000&&data!=0x00) 
		  scc->Write(offset,0x3a);
      else
		  scc->Write(offset,data);
    } 
    else if((0x9800<=offset&&offset<=0x98FF)||(0xB800<=offset&&offset<=0xB8FF))
    {
		 scc->Write(offset,data);
    }

	this->memspace[offset & 0xffff] = data & 0xff;
}

/******************************************************
					I/O Memory Space
******************************************************/

UINT8 CKSSMMU_IO::Read8(unsigned long offset) {
	offset &= 0xff;

	//Msg("I/O Read: %02X\n",offset);
	if (offset == 0xa2) return ay->Read(0);

	return 0;
}

void CKSSMMU_IO::Write8(unsigned long offset, unsigned char data) {
	offset &= 0xff;
	
	//Msg("I/O Write: %02X -> %02X\n",offset, data);
	switch (offset) {
		
		// 0xA0, 0xA1: AY8910 writes
		case 0xA0:
		case 0xA1:
			ay->Write(offset & 1,data);
			break;

		// 0xFE: Bank switch
		case 0xFE:
			if (isUsing16KBBanks) {
				// Get the bank base
				
				UINT32 baseaddr = (data * 0x4000) - (this->first_bank * 0x4000);
				Msg("Bankswitch! Bank id %d, first bank in KSS %d, offset %d\n",data, first_bank, baseaddr);
				memcpy(prgspace->memspace + 0x8000, banked_code->GetRawMemory() + baseaddr, 0x4000);
			}

		default:
			break;


	};

}